package helpers;

import java.util.TreeMap;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class SiteAnalyticHelper {
	
	private Document doc ;
	
	TreeMap check = new TreeMap();
	
	public SiteAnalyticHelper(String content) {
		doc = Jsoup.parse(content);
	}
	
	public String getTitle() {
		String title = "";
		
		try {
            title = doc.select("title").first().text();
        } catch (Exception e) {
            this.check.put("title", "Can't get info title");
        }
		
		return title;
	}
	
	public String getDescription() {
		String description = "";
		try {
            description = doc.select("meta[name=description]").first().attr("content");
        } catch (Exception e) {
            try {
                description = doc.select("meta[http-equiv=description]").first().attr("content");
            } catch (Exception e2) {
                if(doc.select("body").first().text().length() > 260)
                {
                    description = doc.select("body").first().text().substring(0,250).replaceAll("[ ]+[\\w\\W]{0,10}+$", "")+" ...";
                } else {
                    description = doc.select("body").first().text();
                }
            }
        }
        
        return description;
	}
	
	public String getKeywords() {
		String keywords = "";
		
		try {
            keywords = doc.select("meta[name=keywords]").first().attr("content");
        } catch (Exception e) {
            try {
                keywords = doc.select("meta[http-equiv=keywords]").first().attr("content");
            } catch (Exception e2) {
                this.check.put("keywords", "Can't get info keywords");
            }        
        }
		
		return keywords;
	}
	
	public int countHeading(String name) {
		int result = doc.select(name).size();
		return result;
	}
	
	public int countImage() {
		int result = doc.select("img").size();
		return result;
	}
	
	public int countAltImageEmpty() {
		int count = 0;
		Elements els = doc.select("img");
		
		for (int i = 0; i < els.size(); i++) {
			if (!els.get(i).hasAttr("alt")) {
				count ++;
			}
		}
		
		return count;
	}
	
	public String getCharset() {
		String charset = "UTF-8";
		
		int index = doc.select("meta").toString().toLowerCase().indexOf("charset=");
        if (index != -1) {
        	charset = doc.select("meta").toString().substring(index + 8).replaceAll("[^\\'\\\"0-9a-zA-Z\\-\\_]+[\\w\\W]+", "").replaceAll("[\\'\\\"]+", "");
        }
        
        return charset;
	}
}
